package com.ruoyi.iot.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.iot.domain.CameraPreviewModel;
import com.ruoyi.iot.domain.PioltDevice;
import com.ruoyi.iot.domain.YcDeviceData;
import com.ruoyi.iot.domain.YcPushData;
import com.ruoyi.iot.service.IPioltDeviceService;
import com.ruoyi.iot.service.IotDeviceDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//http://120.46.141.64/prod-api/yc/data/push
//http://120.46.141.64/prod-api/yc/data/push
@RestController
@RequestMapping("/yc/data/")
public class YcIotPushController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(YcIotPushController.class);
    @Autowired
    private IPioltDeviceService pioltDeviceService;
    @Autowired
    private IotDeviceDataService iotDeviceDataService;

    @PostMapping(value = "/push")
    public AjaxResult pushData(@RequestBody List<YcPushData> datas)
    {
        logger.info("receive push data........");
        if(datas==null){
            return  AjaxResult.error("data is empty");
        }
        datas.stream().forEach(data->{
            PioltDevice device = pioltDeviceService.selectPioltDeviceByDeviceCode(data.getDeviceId());
            if(device == null){
                //add device to pg
                device = new PioltDevice();
                device.setDeviceCode(data.getDeviceId());
                device.setDeviceName(data.getDeviceName());
                Long userId = 1764970845892575232l;
                device.setUserId(userId);
                device.setDeviceType(3l);
                device.setDeviceTypeCode("trjc");//土壤监测
                device.setDeviceSeries(data.getDeviceId());
                device.setDeviceZbX(data.getDevicePointx());
                device.setDeviceZbY(data.getDevicePointy());
                pioltDeviceService.insertPioltDevice(device);
            }
            data.getDataValues().stream().forEach(item ->{
                YcDeviceData deviceData = new YcDeviceData();
                deviceData.setDeviceCode(data.getDeviceId());
                deviceData.setCjrq(item.getVarDate());
                deviceData.setVarId(item.getVarId());
                deviceData.setVarName(item.getVarName());
                deviceData.setChannelId(item.getChannelId());
                deviceData.setCjData(item.getValue());
                deviceData.setVarUnit(item.getVarUnit());
                deviceData.setFormatValue(item.getFormatValue());
                iotDeviceDataService.insertDeviceData(deviceData);
            });
        });
        return success("推送数据成功");
    }
}
